Java进阶-finally 语句块

  1. finally 语句块可以直接和 try 语句块联用,try...finally...
  2. try...catch...finally... 也可以
  3. finally 语句块中的代码是一定会执行的
  4. finally 语句块是一定会执行的,所以通常在程序中为了保证某资源一定会释放,所以一般在语句块中释放资源

基础例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class ExceptionTest06 {

public static void main(String[] args) {
// try {
// System.out.println("AB"); // AB
// return;
// } finally {
// System.out.println("66"); // 66
// }

// try {
// FileInputStream fils = new FileInputStream("a");
//
// System.out.println("AB"); // 不执行
// } finally {
// System.out.println("66"); // 存疑:不输出。但是教程和百度都说会执行,以后再看看
// }

// 在执行 finally 语句块之前退出了 JVM,则 finally 语句块不会执行
try {
// 退出 JVM
System.exit(0);
} finally {
System.out.println("66"); // 不执行
}
}
}

深入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package test0222;

public class ExceptionTest07 {

public static void main(String[] args) {
int i = m1();
System.out.println(i); // 10
}

private static int m1() {
int i = 10;
try {
return i;
} finally {
i++;
System.out.println("m1的i=" + i); // m1的i=11
}
}
}

神奇的事发生了,两个i不一样,为啥呢,以下是m1()的执行原理

1
2
3
4
5
6
7
8
int i = 10;
try {
int temp = i;
return temp;
} finally {
i++;
System.out.println("m1的i=" + i); // m1的i=11
}

释放资源

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ExceptionText08 {

public static void main(String[] args) {
// 必须放在外边声明
FileInputStream fils = null;

try {
fils = new FileInputStream("a");
} catch (FileNotFoundException e) {
e.printStackTrace();
}

finally {
// 为了保证资源一定会被释放
if (fils != null) {
try {
fils.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
}
}